package com.leyou.upload.service;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Service
@Slf4j
public class UploadService {

    private static final List<String> ALLOW_TYPES = Arrays.asList("image/png", "image/jpeg");

    public String uploadImage(MultipartFile file) {
        //图片信息校验
        try {
            String type = file.getContentType();
            if (!ALLOW_TYPES.contains(type)) {
                log.error("文件类型不匹配");
                throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
            }
            BufferedImage image = ImageIO.read(file.getInputStream());
            if (image == null) {
                log.error("文件类型不匹配");
                throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
            }
            File dir = new File("/Users/ryoukou/Desktop/乐优商城/资料/upload");
            if (!dir.exists()) {
                dir.mkdirs();
            }
            file.transferTo(new File(dir,file.getOriginalFilename()));
            String url = "http://image.leyou.com/upload/" + file.getOriginalFilename();
            return url;
        //校验图片内容
        //保存图片
        } catch (IOException e) {
            e.printStackTrace();
            throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
        }


    }
}
